using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

using Walkmen.Util;

namespace Walkmen.ID3v2
{
    public enum ID3v2Encoding: byte
    {
        ISO88591 = 0x00,
        Unicode = 0x01,
        BigEndianUnicode = 0x02
    }

    public abstract class ID3v2Frame
    {
        private string _frameId;
        private int _size;
        private short _flag;

        public string FrameId
        {
            get { return _frameId; }
            set { _frameId = value; }
        }

        public int Size
        {
            get { return _size; }
            set { _size = value; }
        }

        public short Flag
        {
            get { return _flag; }
            set { _flag = value; }
        }

        public byte[] ToArray()
        {
            using (MemoryStream stream = new MemoryStream())
            {
                byte[] frameId = Encoding.ASCII.GetBytes(_frameId);
                stream.Write(frameId, 0, frameId.Length);

                byte[] value = CreateValue();

                byte[] size = NumericUtils.WriteInt32(value.Length);
                stream.Write(size, 0, size.Length);

                byte[] flag = NumericUtils.WriteShort(_flag);
                stream.Write(flag, 0, flag.Length);

                stream.Write(value, 0, value.Length);

                return stream.ToArray();
            }
        }

        protected abstract byte[] CreateValue();

        protected static Encoding CodeToEncoding(ID3v2Encoding code)
        {
            switch (code)
            {
                case ID3v2Encoding.ISO88591:
                    return Encoding.Default;
                case ID3v2Encoding.Unicode:
                    return new UnicodeEncoding(false, true);
                case ID3v2Encoding.BigEndianUnicode:
                    return new UnicodeEncoding(true, true);
                default:
                    return Encoding.Default;
            }
        }
    }
}
